package com.usian.admin.gateway.filter;

import com.usian.common.dtos.Payload;
import com.usian.common.util.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Fay
 * @date 2022/7/5&11:21
 */
@Component
public class AuthFilter implements GlobalFilter,Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求
        ServerHttpRequest request = exchange.getRequest();
        //获取响应
        ServerHttpResponse response = exchange.getResponse();
        //获取请求的路径  获取的为后面的地址
        String path = request.getURI().getPath();
        //如果包含login/in的话说明是登录 直接放行
        if (path.contains("/login/in")){
            return chain.filter(exchange);
        }
        //如果不包含的话要去验证token是否存在
        //对token进行校验
        String token = request.getHeaders().getFirst("token");
        //token是否存在
        if (StringUtils.isEmpty(token)){
            //如果为空的话返回401状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //如果存在的话进行token校验
        try {
            Payload payload = JwtUtils.getInfoFromToken(token);
            //返回可用的话获取id将id放入请求头中
            Integer userId = payload.getUserId();
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", String.valueOf(userId));
            }).build();
            exchange.mutate().request(serverHttpRequest).build();
        } catch (Exception e) {
            e.printStackTrace();
            //不可用抛出异常的话返回token过期 返回401状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
